package com.ptmall.app.ui.activity;

import android.Manifest;
import android.app.Application;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;

import com.ptmall.app.App;
import com.ptmall.app.R;
import com.ptmall.app.base.BaseMvpActivity;
import com.ptmall.app.base.PermissionListener;
import com.ptmall.app.bean.model.db.Account;
import com.ptmall.app.bean.model.db.DBHelper;
import com.ptmall.app.bean.model.db.dao.AccountDao;
import com.ptmall.app.net.HttpMethods;
import com.ptmall.app.net.api.ApiDataRepository;
import com.ptmall.app.net.api.ApiService;
import com.ptmall.app.net.base.ApiNetResponse;
import com.ptmall.app.net.base.Request;
import com.ptmall.app.net.base.Result;
import com.ptmall.app.net.okhttp.BusinessResponse;
import com.ptmall.app.net.okhttp.OkHttps;
import com.ptmall.app.utils.AllUtils;
import com.ptmall.app.utils.FileUtils;
import com.ptmall.app.utils.GlideUtil;
import com.ptmall.app.utils.UriUtil;
import com.ptmall.app.view.TitleBarView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class InfoActivity extends BaseMvpActivity implements View.OnClickListener, BusinessResponse {

    TitleBarView titlebar;

    ImageView toppic;

    PopupWindow popupWindow;
    private View popView;

    private Uri cropImageUri;
    private Uri takePicUri;
    private final int CROP_IMG_WIDTH = 700;
    private final int CROP_IMG_HEIGHT = 700;

    private final int TAKE_PICTURE = 0x000001;
    private final int CHOOSE_PICTURE = 0x000002;
    private final int CROP_SMALL_PICTURE = 0x000003;

    private AlertDialog.Builder builder;

    private String[] VIDEO_PERMISSION = {
            Manifest.permission.CAMERA,
            //Manifest.permission.RECORD_AUDIO,
            //Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};

    ApiDataRepository apiDataRepository = ApiDataRepository.getInstance();

    private AccountDao mAccountDao = DBHelper.getInstance().getAccountDao();
    RelativeLayout rel_nickname;


    private OkHttps okHttps;

    Account account;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setView(R.layout.activity_personal);
    }

    @Override
    public void initViews() {
        toppic = (ImageView) findViewById(R.id.toppic);
        titlebar = (TitleBarView) findViewById(R.id.titlebar);
        rel_nickname = (RelativeLayout) findViewById(R.id.nickname);

        titlebar.setOnTitleBarClickListener(new TitleBarView.TitleBarClickListener() {
            @Override
            public void leftClick() {
                finish();
            }

            @Override
            public void rightClick() {

            }
        });

        okHttps = new OkHttps(this);
        okHttps.addResponseListener(this);
        toppic.setOnClickListener(this);

    }

    @Override
    public void initEvents() {

        rel_nickname.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final EditText editText = new EditText(getActivity());
                editText.setHint(account.getNickName());
                builder = new AlertDialog.Builder(getActivity()).setTitle("请输入昵称").setView(editText)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                if (TextUtils.isEmpty(editText.getText().toString())) {
                                    return;
                                }
                                Map<String, String> map = new HashMap<>();
                                map.put("nickName", editText.getText().toString());
                                apiDataRepository.nickNameEdit(map, new ApiNetResponse<Object>() {
                                    @Override
                                    public void onSuccess(Object data) {
                                        showMsg("修改成功");
                                        getData();
                                    }
                                });
                            }
                        });
                builder.create().show();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        getData();

    }

    private void getData() {
        apiDataRepository.getUserInfo(null, new ApiNetResponse<Account>() {
            @Override
            public void onSuccess(Account data) {
                account = data;

                GlideUtil.showImg(getContext(), data.image_head, toppic);

            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.toppic:
                requestRuntimePermisssions(VIDEO_PERMISSION, new PermissionListener() {
                    @Override
                    public void onGranted() {//同意
                        pop();
                    }

                    @Override
                    public void onDenied(List<String> deniedList) {
                    }
                });

                break;

            case R.id.btn1://拍照
                takePicUri = getSomeUri();
                Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                openCameraIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, takePicUri);
                startActivityForResult(openCameraIntent, TAKE_PICTURE);
                popupWindow.dismiss();
                break;
            case R.id.btn2://本地相册
                Intent openAlbumIntent = new Intent(
                        Intent.ACTION_PICK);
                openAlbumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                //用startActivityForResult方法，待会儿重写onActivityResult()方法，拿到图片做裁剪操作
                startActivityForResult(openAlbumIntent, CHOOSE_PICTURE);
//                intent = new Intent(PersonalData.this,
//                        AlbumActivity.class);
//                startActivity(intent);
                popupWindow.dismiss();
                break;
            case R.id.btn_cancel:
                popupWindow.dismiss();
                break;
        }
    }


    private void pop() {
        if (null == popupWindow) {
            if (null == popView) {
                popView = LayoutInflater.from(this).inflate(R.layout.personaldata_pop, null);
                popView.findViewById(R.id.btn1).setOnClickListener(this);
                popView.findViewById(R.id.btn2).setOnClickListener(this);
                popView.findViewById(R.id.btn_cancel).setOnClickListener(this);
            }
//            View view = LayoutInflater.from(this).inflate(R.layout.personaldata_pop, null);
            popupWindow = new PopupWindow(popView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
            popupWindow.setAnimationStyle(R.style.dialogAnim);
            popupWindow.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#00000000")));
            AllUtils.backgroundAlpha(0.5f, getWindow());
            popupWindow.showAtLocation(popView, Gravity.BOTTOM, 0, 0);
            popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    AllUtils.backgroundAlpha(1.0f, getWindow());
                }
            });
            //popupWindow.showAtLocation(rootView, Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
        } else {
            AllUtils.backgroundAlpha(0.5f, getWindow());
            popupWindow.showAtLocation(popView, Gravity.BOTTOM, 0, 0);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case TAKE_PICTURE:
//                        String fileName = String.valueOf(System.currentTimeMillis());
//                        Bitmap bm = (Bitmap) data.getExtras().get("data");
//                        String path = FileUtils.saveBitmap(bm);
//                        if (null != path) {
//                            File f = new File(path);
//                            if (f.exists()) {//存在的话 保存成功
//                                //启动图片剪切
//                                cutImage(UriUtil.getFileUri(PersonalData.this,f)/* Uri.fromFile(f)*/);
//                            }
//                        }
                    if (null != takePicUri) {
                        cropImageUri(takePicUri, CROP_IMG_WIDTH, CROP_IMG_HEIGHT, CROP_SMALL_PICTURE);
                    }
                    break;
                case CHOOSE_PICTURE:
                    //cutImage(data.getData());
                    cropImageUri(data.getData(), CROP_IMG_WIDTH, CROP_IMG_HEIGHT, CROP_SMALL_PICTURE);
                    break;
                case CROP_SMALL_PICTURE:
                    setImageToView(data);
                    break;

                default:
                    break;
            }
        }
    }


    /**
     * 设置头像
     */
    protected void setImageToView(Intent data) {
        Bundle extras = data.getExtras();
        Bitmap bitmap = null;
        if (extras != null) {
            bitmap = extras.getParcelable("data");
        }
        if (null == bitmap) {
            try {
                bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), cropImageUri);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (null == bitmap) {
            return;
        }

        FileUtils.saveBitmap(bitmap, "123456");
//        Map<String,Object> map = new HashMap<>();
//        map.put("image",new File(path));
//        map.put("memberId",App.getInstance().getAccount().memberId+"");
//        apiDataRepository.uploadFile(path, new Consumer<Result<String>>() {
//            @Override
//            public void accept(Result<String> stringResult) throws Exception {
//                if (stringResult != null) {
//                    if (stringResult.isSuccess()) {
//                        App.getInstance().getAccount().setImage_head(stringResult.getData());
//                        Account account = new Account();
//                        //account.setIco(uploadResult.getBaseUrl()+uploadResult.getFile());
//                        account.setImage_head(stringResult.getData());
//                        update(account);
//                        showMsg("上传成功");
//                    }
//                } else {
//                    showMsg("处理失败");
//                }
//
//            }
//        });

        okHttps.postAsynFile(HttpMethods.BASE_URL + "User/headChange", new File(FileUtils.SDPATH + "123456.JPEG"), true, 1);

    }

    /**
     * 更新用户信息
     *
     * @param account
     */
    private void update(Account account) {


    }

    /**
     * 裁剪图片
     *
     * @param uri
     * @param outputX
     * @param outputY
     * @param requestCode
     */
    private void cropImageUri(Uri uri, int outputX, int outputY, int requestCode) {
        String fileName = FileUtils.SDPATH + String.valueOf(System.currentTimeMillis()) + ".jpg";
        String local = FileUtils.SDPATH;
        File folder = new File(local);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        cropImageUri = Uri.fromFile(new File(fileName));
//        cropImageUri = getSomeUri();

        // cropImageUri = uri;
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        //是否裁剪
        intent.putExtra("crop", "true");
        //设置xy的裁剪比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        //设置输出的宽高
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        //是否缩放
        intent.putExtra("scale", false);
        //输入图片的Uri，指定以后，可以在这个uri获得图片
        intent.putExtra(MediaStore.EXTRA_OUTPUT, cropImageUri);
        //是否返回图片数据，可以不用，直接用uri就可以了
        intent.putExtra("return-data", false);
        //设置输入图片格式
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        //是否关闭面部识别
        intent.putExtra("noFaceDetection", true); // no face detection
        //启动
        startActivityForResult(intent, requestCode);
    }

    /**
     * 创建任一Uri
     *
     * @return
     */
    private Uri getSomeUri() {
        String fileName = FileUtils.SDPATH + String.valueOf(System.currentTimeMillis()) + ".jpg";
        String local = FileUtils.SDPATH;
        File folder = new File(local);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        return UriUtil.getFileUri(getContext(), new File(fileName));
    }


    @Override
    public void OnMessageResponse(int id, String jo) {
        switch (id) {
            case 1:
                getData();
                break;
        }
    }
}
